package com.lianyu.wangyiyun.utils;

import android.content.ContentResolver;
import android.database.Cursor;
import android.provider.MediaStore;

import com.lianyu.wangyiyun.model.Mp3Info;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Chen Yuguang
 * @date 2021/5/9 19:24
 */
public class FindLocalSongs {

    public static List<Mp3Info> getMp3Infos(ContentResolver contentResolver) {
        String selection = MediaStore.Audio.Media.IS_MUSIC + " = ? " + " AND " + MediaStore.Audio.Media.MIME_TYPE + " LIKE ? ";
        String[] selectionArgs = {Integer.toString(1), "audio/mpeg"};
        Cursor cursor = contentResolver.query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, selection, selectionArgs,
                MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
        List<Mp3Info> mp3Infos = new ArrayList<>();
        for (int i = 0; i < cursor.getCount(); i++) {
            //新建一个歌曲对象,将从cursor里读出的信息存放进去,直到取完cursor里面的内容为止.
            Mp3Info mp3Info = new Mp3Info();
            cursor.moveToNext();
            //音乐id
            long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
            //音乐标题
            String title = cursor.getString((cursor.getColumnIndex(MediaStore.Audio.Media.TITLE)));
            //艺术家
            String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
            //时长
            long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
            //文件路径
            String url = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
            //只把30s以上的音乐添加到集合当中
            if (duration / (1000 * 30) >= 1) {
                mp3Info.setId(id);
                mp3Info.setTitle(title);
                mp3Info.setArtist(artist);
                mp3Info.setUrl(url);
                mp3Infos.add(mp3Info);
            }
        }
        cursor.close();
        return mp3Infos;
    }

}